//
//  LocationService.m
//  iNordecaCore
//
//  Created by Janidu Wanigasuriya on 10/9/12.
//  Copyright (c) 2012 Norge-serien. All rights reserved.
//
//  Purpose: A wrapper class to abstract location logic required

#import "LocationService.h"

@interface LocationService ()
@property(nonatomic)CLLocationManager *locationManager;
@end

NSString * const NOTIFICATION_LOCATE = @"LOCATE_NOTIFICATION";

@implementation LocationService

- ( void ) locateMe {
    if ([CLLocationManager locationServicesEnabled]) {
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;
        self.locationManager.distanceFilter = kCLDistanceFilterNone;
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
        [self.locationManager startUpdatingLocation];
    }else{
        //Notify that services are disabled
        [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_LOCATE object:NSLocalizedString(@"err_location_denied",
                                                                                                                @"Access to the location service was denied.")];
        [self stopLocationService];
    }
}

-(void)stopLocationService{
    [self.locationManager stopUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
   
    
    //  if (newLocation.horizontalAccuracy == kCLLocationAccuracyBestForNavigation){ // got a good enough location
    //Post the accurate location
    [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_LOCATE object:newLocation];
    //}
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSString *strError;
	if( [error domain] == kCLErrorDomain ) {
		switch([error code]) {
            case kCLErrorDenied:
                strError = @"Access to the location service was denied.";
                break;
            case kCLErrorLocationUnknown:
                strError = @"Was unable to obtain a location value right now.";
                break;
            default:
                strError = @"Location Error.";
                break;
        }
    } else {
        strError = [@"Error doamin: " stringByAppendingString: error.domain];
		strError = [[strError stringByAppendingString:@" Error Code: "]stringByAppendingString: [[NSNumber numberWithInteger:error.code] stringValue]];
    }
    
    //Notify failure
    [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_LOCATE object:strError];
    [self stopLocationService];
}
@end
